﻿using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace Hu.Core.Domains.Basic.Service
{
    public class HuBaseDbService<HuDbContext> where HuDbContext : DbContext
    {
        private readonly HuDbContext DataContext;

        public HuBaseDbService(HuDbContext context)
        {
            DataContext = context;
        }

        public IQueryable<TEntity> ValidQuery<TEntity>(Expression<Func<TEntity, bool>> predicates) where TEntity : class, new()
        {
            return this.DbSet<TEntity>().Where(predicates);
        }

        public DbSet<TEntity> DbSet<TEntity>() where TEntity : class, new()
        {
            return this.DataContext.Set<TEntity>();
        }

        public async Task<TEntity> GetByIdAsync<TEntity>(int id) where TEntity : class, new()
        {
            return await this.DbSet<TEntity>().FindAsync(id);
        }

        public async Task AddAsync<TEntity>(TEntity entity) where TEntity : class, new()
        {
            await this.DataContext.AddAsync(entity);
            await this.DataContext.SaveChangesAsync();
        }
        /// <summary>
        /// 批量删除 一条删除语句不适用多个删除语句
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="predicate"></param>
        public void DeleteRange<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class, new()
        {
            //this.DataContext.DeleteRangeAsync(predicate);
        }

        /// <summary>
        /// 并发情况下更新
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        public async void UpdateByConcurrent<TEntity>(TEntity entity) where TEntity : class, new()
        {
            this.DataContext.Update(entity);
            try
            {
                await this.DataContext.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                Console.WriteLine("当前值已被他人修改，请重试");
                // 处理并发冲突（如重试或提示用户）
                var entry = ex.Entries.Single();
                var databaseValues = entry.GetDatabaseValues(); // 当前数据库中的值
                var clientValues = entry.Entity;               // 当前客户端尝试提交的值
                // 根据业务逻辑处理（如合并数据或提示用户）
            }
        }
    }
}
